package 链表相交;

import 删除链表的倒数第N个结点.Demo19;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 链表相交
 * @date 2022/10/23 10:50
 */
public class Demo160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode preA=new ListNode(-1);
        int countA=0;
        preA.next=headA;
        ListNode curA=preA;
        ListNode preB=new ListNode(-1);
        preB.next=headB;
        int countB=0;
        ListNode curB=preB;
        while (curA.next!=null){
            countA++;
            curA=curA.next;
        }
        while (curB.next!=null){
            countB++;
            curB=curB.next;
        }
        int step=Math.max(countA-countB,countB-countA);
       if(countA>countB){
           while (step>0){
               preA=preA.next;
               step--;
           }
       }else {
           while (step>0){
               preB= preB.next;
               step--;
           }
       }
       while (preA!=null&&preB!=null){
           if(preA==preB){
               return preA;
           }else {
               preA=preA.next;
               preB=preB.next;
           }
       }
       return null;
    }
    public class ListNode {
        int val;
       ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
